package com.markby.fscm.utils;

import com.markby.fscm.common.ResultCodeEnum;
import com.markby.fscm.common.exception.SSCMException;
import com.markby.fscm.constant.Constants;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration = 60 * 60 * 1000L;
    private static final SecretKey tokenSignKey = Keys.hmacShaKeyFor(Constants.JWT_KEY.getBytes());

    public static String createToken(String randomNum, String source) {
        String uuid = IdUtils.fastUUID();

        String token = Jwts.builder().
                setSubject(Constants.SUBJECT_CONNECT).
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim(Constants.CLAIM_UUID, uuid).
                claim(Constants.CLAIM_RANDOM_NUM, randomNum).
                claim(Constants.CLAIM_SOURCE, source).
                signWith(tokenSignKey).
                compact();
        return token;
    }

    public static Claims parseToken(String token) {

        if (token == null) {
            throw new SSCMException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new SSCMException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new SSCMException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

}